package com.zan.zanchat.common.common.event.listener;

import com.zan.zanchat.common.common.event.UserBlackEvent;
import com.zan.zanchat.common.common.event.UserOnlineEvent;
import com.zan.zanchat.common.user.dao.UserDao;
import com.zan.zanchat.common.user.domain.entity.User;
import com.zan.zanchat.common.user.domain.enums.UserActiveStatusEnum;
import com.zan.zanchat.common.user.service.IpService;
import com.zan.zanchat.common.user.service.cache.UserCache;
import com.zan.zanchat.common.websocket.service.WebSocketService;
import com.zan.zanchat.common.websocket.service.adapter.WebSocketAdapter;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

/**
 * @Author Zan
 * @Create 2024/3/17 19:57
 * @Description :
 */
@Component
public class UserBlackListener {

    @Resource
    private WebSocketService webSocketService;

    @Resource
    private UserDao userDao;

    @Resource
    private UserCache userCache;

    /**
     * 发送消息
     */
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    public void sendMsg(UserBlackEvent event) {
        User user = event.getUser();
        webSocketService.sendMsgToAll(WebSocketAdapter.buildBlack(user));
    }

    /**
     * 修改用户状态
     * @param event
     */
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    public void changeUserStatus(UserBlackEvent event) {
        // 拉黑用户
        userDao.invalidUid(event.getUser().getId());
    }

    /**
     * 清除缓存
     */
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    public void evictCache(UserBlackEvent event) {
        userCache.evictBlackMap();
    }
}
